/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ABMRubros.java
 *
 * Created on 18/07/2011, 14:18:44
 */

package ventanas;

import conexiones.AdministradorDeConexiones;
import dao.RubrosDao;
import java.sql.Connection;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import modelo.Rubro;

/**
 *
 * @author Cristian Perez
 */
public class ABMRubros extends javax.swing.JDialog {

    DefaultListModel modeloRubros = new DefaultListModel();

    /** Creates new form ABMRubros */
    public ABMRubros(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        inicializarFormulario();
        jList1.setModel(modeloRubros);
        modeloRubros = (DefaultListModel) jList1.getModel();
        cargarLista();
    }

    public ABMRubros(AltaArticulos ventaAltaArt, boolean b) {
        //throw new UnsupportedOperationException("Not yet implemented");
        super(ventaAltaArt, b);
        initComponents();

        inicializarFormulario();
        jList1.setModel(modeloRubros);
        modeloRubros = (DefaultListModel) jList1.getModel();
        cargarLista();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtRubro = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        btnAlta = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Rubros");

        jList1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Lista de rubros", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 2, 11))); // NOI18N
        jList1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });
        jList1.addHierarchyListener(new java.awt.event.HierarchyListener() {
            public void hierarchyChanged(java.awt.event.HierarchyEvent evt) {
                jList1HierarchyChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel1.setFont(new java.awt.Font("Tahoma", 3, 12));
        jLabel1.setText("Nombre del rubro: ");

        txtRubro.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        txtRubro.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtRubroFocusLost(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtRubro, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                    .addComponent(txtRubro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        btnAlta.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnAlta.setText("Nuevo Rubro");
        btnAlta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAltaActionPerformed(evt);
            }
        });

        btnEliminar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnAceptar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnSalir.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnSalir.setText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        btnModificar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnModificar.setText("Modificar");
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(2, 2, 2)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(btnAlta, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnModificar, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAlta, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE)
                    .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-683)/2, (screenSize.height-297)/2, 683, 297);
    }// </editor-fold>//GEN-END:initComponents

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnSalirActionPerformed

    private void btnAltaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAltaActionPerformed
        // TODO add your handling code here:
        txtRubro.setEnabled(true);
        txtRubro.setText("");
        txtRubro.requestFocus();
        btnEliminar.setEnabled(false);
        btnModificar.setEnabled(false);
        btnAceptar.setEnabled(true);
        btnCancelar.setEnabled(true);
        btnAlta.setEnabled(false);
        jList1.clearSelection();
    }//GEN-LAST:event_btnAltaActionPerformed

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        // TODO add your handling code here:
        if(txtRubro.getText().trim().equals("")) {
             JOptionPane.showMessageDialog(this, "Debe ingresar un nombre de Rubro", "Error", JOptionPane.WARNING_MESSAGE);
             txtRubro.requestFocus();
       }
       else if (jList1.getSelectedIndex() == -1){
                guardarRubro();
       }
       else {
                ModificarRubro();
       }
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        actualizarFormulario();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        Connection conn = null;
        if (jList1.getSelectedIndex() == -1) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar algun Rubro para Eliminar", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
        else {
            try {
                conn = AdministradorDeConexiones.obtenerConexion();
                //Obtengo la posicion en la lista del elemento a eliminar
                int pos = jList1.getSelectedIndex();
                //Le pido al modelo la instancia del perfil a eliminar
                Rubro rubro = (Rubro) modeloRubros.get(pos);

                //Verificamos la existencia del rubro en los articulos
                if (RubrosDao.getInstance().verificarExistenciaRubro(conn, rubro.getCod())) {
                    JOptionPane.showMessageDialog(this, "Existen articulos asignados al rubro que desea eliminar", "Error", JOptionPane.INFORMATION_MESSAGE);
                }
                else {
                    // Consulta si desea eliminar el perfil
                    int rta = JOptionPane.showConfirmDialog(this,
                                        "Esta seguro de eliminar el rubro?",
                                        "Eliminar",
                                        JOptionPane.YES_NO_OPTION);
                    //Si la opcion seleccionada es NO retorna y no hace nada
                    if(rta == JOptionPane.NO_OPTION)
                         return;

                    //Si la opcion seleccionada es SI elimina el rubro
                    RubrosDao.getInstance().eliminar(conn, rubro);
                    txtRubro.setText("");
                }
            }catch(Exception e) {e.printStackTrace();}

            //Actualizo el estado de la lista
            modeloRubros.removeAllElements();
            cargarLista();
            inicializarFormulario();
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
        // TODO add your handling code here:
        if (jList1.getSelectedIndex() == -1) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar algun Rubro para Modificar", "Error", JOptionPane.INFORMATION_MESSAGE);
        }
        else {
            txtRubro.setEnabled(true);
            txtRubro.setText(jList1.getSelectedValue().toString());
            txtRubro.requestFocus();
            btnEliminar.setEnabled(false);
            btnModificar.setEnabled(false);
            btnAceptar.setEnabled(true);
            btnCancelar.setEnabled(true);
            btnAlta.setEnabled(false);
        }
    }//GEN-LAST:event_btnModificarActionPerformed

    private void txtRubroFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtRubroFocusLost
        // TODO add your handling code here:
    }//GEN-LAST:event_txtRubroFocusLost

    private void jList1HierarchyChanged(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_jList1HierarchyChanged
        // TODO add your handling code here:
    }//GEN-LAST:event_jList1HierarchyChanged

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
        // TODO add your handling code here:
        if (jList1.getSelectedIndex() != -1) {
            txtRubro.setText(jList1.getSelectedValue().toString());
        }
    }//GEN-LAST:event_jList1ValueChanged

    /**
    * @param args the command line arguments
    */
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnAlta;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnModificar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField txtRubro;
    // End of variables declaration//GEN-END:variables

    private void inicializarFormulario() {
        txtRubro.setEnabled(false);
        btnAceptar.setEnabled(false);
        btnCancelar.setEnabled(false);
        jList1.clearSelection();
    }

    private void cargarLista() {
        Connection conn = null;
        ArrayList listaRubros = new ArrayList();
        try {
            conn = AdministradorDeConexiones.obtenerConexion();
            listaRubros = RubrosDao.getInstance().getTodos(conn);
            for (int i=0; i < listaRubros.size(); i++) {
                modeloRubros.addElement(listaRubros.get(i));
            }
        }catch(Exception e) {e.printStackTrace();}
    }

    private void guardarRubro() {
        Connection conn = null;
            try {
                conn = AdministradorDeConexiones.obtenerConexion();
                Rubro rub = new Rubro(txtRubro.getText().toUpperCase().trim());
                RubrosDao.getInstance().insertar(conn, rub);
                modeloRubros.addElement(rub);
                txtRubro.setText("");
                txtRubro.setEnabled(false);
                btnAceptar.setEnabled(false);
                btnCancelar.setEnabled(false);
                btnAlta.setEnabled(true);
                btnEliminar.setEnabled(true);
                btnModificar.setEnabled(true);
            }catch(Exception e) {e.printStackTrace();}
            finally {
                JOptionPane.showMessageDialog(this, "El Rubro ha sido guardado correctamente!!!", "Guardar", JOptionPane.INFORMATION_MESSAGE);
            }
    }

    private void ModificarRubro() {
        Connection conn = null;
            try {
                conn = AdministradorDeConexiones.obtenerConexion();
                Rubro rub = (Rubro) modeloRubros.getElementAt(jList1.getSelectedIndex());
                rub.setNombre(txtRubro.getText().toUpperCase().trim());
                RubrosDao.getInstance().modificar(conn, rub);
                //ACtualizar lista
                txtRubro.setText("");
                txtRubro.setEnabled(false);
                btnAceptar.setEnabled(false);
                btnCancelar.setEnabled(false);
                btnAlta.setEnabled(true);
                btnEliminar.setEnabled(true);
                btnModificar.setEnabled(true);
                //Actualizo el estado de la lista
                modeloRubros.removeAllElements();
                cargarLista();
                inicializarFormulario();
            }catch(Exception e) {e.printStackTrace();}
            finally {
                JOptionPane.showMessageDialog(this, "El Rubro ha sido Modificado correctamente!!!", "Modificar", JOptionPane.INFORMATION_MESSAGE);
            }
    }


    private void actualizarFormulario() {
        jList1.clearSelection();
        txtRubro.setText("");
        txtRubro.setEnabled(false);
        btnEliminar.setEnabled(true);
        btnModificar.setEnabled(true);
        btnAceptar.setEnabled(false);
        btnCancelar.setEnabled(false);
        btnAlta.setEnabled(true);
    }
}
